<template>
  <div class="default-main ba-table-box">
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="[
        'refresh',
        'add',
        'edit',
        'remove',
        'comSearch',
        'columnDisplay',
      ]"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" :pagination="false" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <PopupForm />
  </div>
</template>
<script setup lang="ts">
import { ref, provide, onMounted, reactive, watch, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { QualityDefect } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import PopupForm from "./popupForm.vue";
import { useMenu } from "@/store/backend/SysM/menu";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useRoute, useRouter } from "vue-router";
import { getDictData } from "@/utils/common";
import Tag from "./components/tag.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import { useNavTabs } from "@/store/navTabs";
import { useQualityDefect } from "@/store/backend/Check/defect";
import { useBomDict } from "@/store/backend/BomM/bomDict";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const router = useRouter();
const dictionary = useDictionary();
const route = useRoute();
const navTabs = useNavTabs();
const defect = useQualityDefect();
const bomD = useBomDict();

const state: { statusDict: anyObj } = reactive({
  statusDict: {},
});

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + QualityDefect)
      ? (navTabs as any).pageSizeMap.get(route.path + QualityDefect)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(QualityDefect), //this.api = api菜单管理相关
  {
    pk: "id",
    expandAll: false,
    dblClickNotEditColumn: [undefined, "status"],
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("materialCode"),
        label: "物料编码",
        prop: "materialCode",
        align: "left",
      },
      // {
      //   show: filedShowOff("icon"),
      //   label: "图标",
      //   prop: "icon",
      //   align: "center",
      //   width: "60",
      //   render: "icon",
      //   default: "el-icon-Minus",
      //   operator: false,
      // },
      {
        show: filedShowOff("materialName"),
        label: "物料名称",
        prop: "materialName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("defectType"),
        label: "缺陷项类型",
        prop: "defectType",
        align: "center",
        render: "customRender",
        customRender: markRaw(Tag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("defectName"),
        label: "缺陷项名称",
        prop: "defectName",
        align: "center",
      },
      {
        show: filedShowOff("defectCode"),
        label: "缺陷项编码",
        prop: "defectCode",
        align: "center",
      },
      {
        show: operatorShowOff([
          route.path + "/edit",
          route.path + "/add",
          route.path + "/remove",
        ]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
    extend: {
      maxHeight: 600,
    },
  },
  // 表单参数
  {
    // 默认表单数据(添加)
    defaultItems: {},
    // 表单字段加载状态
    loading: false,
  },
  // 操作前置方法列表，返回false则取消原操作
  {},
  // 操作后置方法列表，先执行表格本身的查看、删除、编辑、双击、等，再执行本处添加的后置操作
  {}
);

//获取缺陷的字典
const getMenuStatus = () => {
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["defectType"])
  ) {
    dictionary.getDictInfo("sys_quality_defect").then((res: any) => {
      dictionary.moreTags["defectType"] = getDictData(res);
      dictionary.moreTags["defectTypeOrigin"] = res;
      console.log("获取缺陷项类型的字典", dictionary.moreTags);
    });
  }
};
getMenuStatus();

onMounted(() => {
  console.log(router.currentRoute.value);
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(QualityDefect);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {}
  );
});

// 相当于表格的onMounted，也可以在页面的onMounted时执行
// baTable.mount();
// 获取数据，可以在页面的onMounted时执行，也可以比如先请求一个API，再执行获取数据
// baTable.getIndex("menuData");//前置调用
//baTable.getIndex()!.then(() => {
//查看请求完毕（已获取到表格数据）
//  baTable.initSort() // 初始化默认排序（如果需要）
//  baTable.dragSort() // 初始化拖拽排序（如果需要）
//})

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("defect", defect);
provide("bomD", bomD);
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
